package com.ruoyi.config;

import com.alibaba.cloud.commons.lang.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @author: liufei
 * @Desc:
 * @create: 2024-11-07 09:31
 **/
@Configuration
public class GatewayConfig implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getPath().toString();
        System.out.println("请求路径："+url);
        String[] SuccessUrl = new String[]{"/user/login","/user/sendCode"};

        for (String s : SuccessUrl) {
            if (s.equals(url)){
                System.out.println("白名单："+url+"   放行");
                return chain.filter(exchange);
            }
        }

        String token = request.getHeaders().getFirst("token");

        Claims claims = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody();
        Integer userId = claims.get("userId", Integer.class);
        String token1 = stringRedisTemplate.opsForValue().get("token:" + userId);
        if(StringUtils.isEmpty(token1)){
            System.out.println("token过期");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Boolean expire = stringRedisTemplate.expire("token:" + userId, 5, TimeUnit.MINUTES);
        if(expire){
            System.out.println("token刷新成功");
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
